from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
from app.core.utils import generate_orderid

class CEFRequest(BaseModel):
    """CEF 退货交易请求模型"""
    trans_code: str = Field(default="CEF", description="交易代码")
    appid: str = Field(..., max_length=3, description="交易来源")
    pan: str = Field(..., max_length=19, description="卡号")
    orderid: Optional[str] = Field(None, max_length=30, description="订单流水")
    trans_date: Optional[str] = Field(None, max_length=8, description="交易日期")
    trans_time: Optional[str] = Field(None, max_length=6, description="交易时间")
    trans_amt: str = Field(..., max_length=12, description="交易金额（分）")
    merno: str = Field(..., max_length=15, description="商户号")
    terminal: str = Field(..., max_length=8, description="终端号")
    cur_code: Optional[str] = Field(default="156", max_length=3, description="货币代码")
    pay_order: str = Field(..., max_length=20, description="外部订单号")
    org_trans_sn: str = Field(..., max_length=30, description="原交易流水号")
    org_rrn: str = Field(..., max_length=12, description="原交易参考号")
    pay_org_order: Optional[str] = Field(None, max_length=20, description="原交易外部订单号")
    pay_merchant: Optional[str] = Field(None, max_length=20, description="外部商户号")
    pay_mername: Optional[str] = Field(None, max_length=120, description="外部商户名")

    def prepare_data(self) -> dict:
        """准备交易数据，补充必要字段"""
        now = datetime.now()
        data = self.model_dump(exclude_none=True)
        
        # 补充订单号
        if not self.orderid:
            data["orderid"] = generate_orderid("01")
            
        # 补充交易日期和时间
        if not self.trans_date:
            data["trans_date"] = now.strftime("%Y%m%d")
        if not self.trans_time:
            data["trans_time"] = now.strftime("%H%M%S")
            
        # 转换字段名称
        if "org_trans_sn" in data:
            data["org_trans_sn"] = data.pop("org_trans_sn")
        if "org_rrn" in data:
            data["org_rrn"] = data.pop("org_rrn")
            
        return data

class CEFResponse(BaseModel):
    """CEF 退货交易响应模型"""
    trans_code: str = Field(default="CEF", description="交易代码")
    bank_date: str = Field(..., max_length=8, description="清算日期")
    resp_code: str = Field(..., max_length=5, description="响应码")
    trans_sn: str = Field(..., max_length=30, description="卡系统流水号")
    rrn: str = Field(..., max_length=12, description="卡系统参考号")
    orderid: str = Field(..., max_length=30, description="请求订单流水")
    pan: str = Field(..., max_length=19, description="卡号")
    error_msg: str = Field(default="", description="错误信息") 